/* Custom javascript 详细介绍请查看官方文档
 * @param {Object} params
 * @property {Array} params.axes  chart options中的轴配置，与拖入的轴对应
 * @property {Object} params.data  接口返回的数据，与轴对应
 * @property {Array} params.data.data 接口返回的原始数据
 * @property {Array} params.data.schema 这里包含了初步加工过的数据，其中的dataUniq是去重并按照配置排好序的
 * @property {number} params.width  容器的宽度
 * @property {number} params.height 容器的高度
 * @property {Function} params.getD3 获取d3工具库, 当前版本7.0.1
 * @property {Function} params.getEcharts 获取echarts，当前版本是4.9，用于写扩展
 * @property {Function} params.useEchartsGL 加载echartsGL, 1.1.2版本
 * @property {Function} params.getThree 获取three.js，当前版本0.132.2
 * @property {Function} params.getTween 获取tween.js，当前版本18.6.4
 * @property {Function} params.createElement 生成一个DOM
 * @property {Function} params.appendChild 向容器添加DOM
 * @property {Function} params.getParentDOM 获取DOM的父元素
 * @property {Function} params.setInnerHTML 设置容器的innerHTML
 * @property {Function} params.bindClickListener 绑定页面点击事件
 * @property {Function} params.onHSClickHandler 触发衡石交互
 * @property {Function} params.getContext 获取canvas的context
 * @property {Object=} params.currentHighlight 当前高亮项
 * @property {Function} params.bindUnmountHandler 绑定卸载时执行的方法，比如卸载组件，清除setTimeout等
 * @property {Array<clickEventData>=} params.currentHighlight.clickEventData 当前高亮项对应的数据
 */
// alert(JSON.stringify(params.data.data));
// alert(JSON.stringify(params.data.schema[0].data))
// alert(JSON.stringify(params.data.schema[1].data))
//   alert(JSON.stringify(params.axes[0]))

console.log(params, 'params')
var axes = params.axes;
if (!axes || axes.length !== 2 || axes[0].axisName !== 'group' || axes[1].axisName !== 'metric') {
  params.setInnerHTML('<div style="text-align:center;line-height:' + params.height + 'px;">'
    +    '<span>缺少维度或指标</span>'
  +  '</div>'
  );
  return;
}
// var myChart = params.getEchartsItem();
//alert(params.getEcharts().dataTool)
let oEchart = params.getEchartsItem(); // echarts.init(document.getElementById('boxplotChart'));

function asc(arr) {
  arr.sort(function (a, b) {
    return a - b;
  });
  return arr;
}
function quantile(ascArr, p) {
  var H = (ascArr.length - 1) * p + 1;
  var h = Math.floor(H);
  var v = +ascArr[h - 1];
  var e = H - h;
  return e ? v + e * (ascArr[h] - v) : v;
}

function prepareBoxplotData(rawData, opt) {
  opt = opt || [];
  var boxData = [];
  var outliers = [];
  var axisData = [];
  var boundIQR = opt.boundIQR;
  var useExtreme = boundIQR === 'none' || boundIQR === 0;

  for (var i = 0; i < rawData.length; i++) {
    axisData.push(i + '');
    var ascList = asc(rawData[i].slice());
    var Q1 = quantile(ascList, 0.25);
    var Q2 = quantile(ascList, 0.5);
    var Q3 = quantile(ascList, 0.75);
    var min = ascList[0];
    var max = ascList[ascList.length - 1];
    var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1);
    var low = useExtreme ? min : Math.max(min, Q1 - bound);
    var high = useExtreme ? max : Math.min(max, Q3 + bound);
    boxData.push([low, Q1, Q2, Q3, high]);

    for (var j = 0; j < ascList.length; j++) {
      var dataItem = ascList[j];

      if (dataItem < low || dataItem > high) {
        var outlier = [i, dataItem];
        opt.layout === 'vertical' && outlier.reverse();
        outliers.push(outlier);
      }
    }
  }

  return {
    boxData: boxData,
    outliers: outliers,
    axisData: axisData
  };
}

// const getRandom = (n, m) => Math.round(Math.random() * (m - n) + n);

const getData = function(legendData, xAxisData){
  const data = []
  const originData = params.data.data || [];
  for (var seriesIndex = 0; seriesIndex < legendData.length; seriesIndex++) {
    var seriesData = [];
    var lItem = legendData[seriesIndex]
    for (var i = 0; i < xAxisData.length; i++) {
      
      var xaItem = xAxisData[i]
      var cate = originData.find(item => item[0] === xaItem);
      if(cate){
        var catenum = cate[1].map(item => item[0])
        seriesData.push(catenum);
      }
    }
    console.log(seriesData, 'seriesData')
    data.push(prepareBoxplotData(seriesData));
  }
  return data
}


const formatter = (params) => {
  if(params.seriesType === 'pictorialBar'){
    return params.seriesName + '<br>' + params.marker + params.data[1]
  }
  if(params.seriesType === 'line'){
    return params.name + '<br>' + params.marker + params.data
  }
  let txt = '';
  txt += params.name + '<br>' 
    + params.marker + '上限值：' + params.data[5] + '<br>' 
   	 + params.marker + '上四分位数：' + params.data[4] + '<br>' 
    + params.marker + '中位数：' + params.data[3] + '<br>' 
    + params.marker + '下四分位数:' + params.data[2] + '<br>' 
    + params.marker + '下限值：' + params.data[1] + '<br>' 
  return txt
}
const legendData = [params.data.schema[1].label] //["北京", "上海", "天津"];
const xAxisData = params.data.schema[0].dataUniq  //[ '中毒', '心脏', '胃病', '胃病1', '胃病2', '胃病3', '胃病4', '胃病5' ]
//console.log(legendData, 'legendData')
//console.log(xAxisData, 'xAxisData')
const data = getData(legendData, xAxisData)

const lineData = data[0].boxData.map(item => {
  return item[2]
})

option = {
  legend: {
    y: "0"
  },
  tooltip: {
    trigger: "item",
    axisPointer: {
      type: "shadow",
    },
    formatter: formatter
  },
  grid: {
    top: "10%"
  },
  xAxis: {
    type: "category",
    splitArea: {
      show: true,
    },
    axisTick: {
      show: false
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      fontSize: 12,
      rotate: 60,
      margin: 5,
      lineOverflow: 'truncate',
      overflow: 'truncate',
      formatter: function(value = '') {
        return value.length > 4 ? value.substr(0, 4) + '...' : value
      }
    },
    data: xAxisData
  },
  yAxis: {
    type: "value",
    name: "Value",
    min: 0,
    max: params.data.schema[1].max + 10
  },
  
  series: [
    ...legendData.map((item, index) => {
      return {
        name: item,
        type: "boxplot",
        data: data[index].boxData,
        itemStyle:{borderColor:'#088AD5'}
      }
    }),
    {
      name: "中位线",
      type: "line",
      data: lineData,
      z: 20
    }
  ],
};
// console.log(data);

oEchart.setOption(option)